package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.pojo.R;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //1.获取URI
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        log.info("当前过滤器拦截的路径为:{}", requestURI);

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };


        if (check(urls, requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        Long loginId = (Long) request.getSession().getAttribute("employee");
        if(loginId!=null){
            filterChain.doFilter(request,response);
            BaseContext.setCurrentId(loginId);
            return;
        }

//        String token = request.getHeader("Authorization");
//
//        if (token != null) {
//            //获得JWT构造器
//            try {
//                System.out.println(token);
//                JwtParser parser = Jwts.parser();
//                Jws<Claims> claimsJws =parser.setSigningKey("123456")
//                                             .parseClaimsJws(token);
//
//                Claims body = claimsJws.getBody();
//                long l = Long.parseLong(body.get("empId").toString()) ;
//                BaseContext.setCurrentId(l);
//                filterChain.doFilter(request, response);
//            } catch (ExpiredJwtException e) {
//                e.printStackTrace();
//            } catch (UnsupportedJwtException e) {
//                e.printStackTrace();
//            } catch (MalformedJwtException e) {
//                e.printStackTrace();
//            } catch (SignatureException e) {
//                e.printStackTrace();
//            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (ServletException e) {
//                e.printStackTrace();
//            }
//            return;
//        }


        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        R r = R.error("NOTLOGIN");

        String rJSON = JSON.toJSONString(r);
        response.getWriter().write(rJSON);
        response.setContentType("application/Json");

    }


    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
